package ncme.auto.framework.core.mybatisplugin;

import ncme.auto.framework.core.dynamicDatasource.configs.DynamicDataSourceConfig;
import ncme.auto.framework.core.dynamicDatasource.utils.ConvertUtil;
import ncme.auto.framework.core.dynamicDatasource.utils.SQLExecutor;
import ncme.auto.framework.core.exceptions.AutoException;
import ncme.auto.framework.core.exceptions.ExceptionEnum;
import ncme.auto.framework.core.utils.BeanUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;

@Component
@Intercepts(
        {
                @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
        }
)
public class CreateTimePlugin extends SQLExecutor implements Interceptor {

    @Autowired
    private ConvertUtil convertUtil;

    @Autowired
    private DynamicDataSourceConfig dataSourceConfig;

    @Value("${auto-framework-config.auto-fill-field.insert-time-fields}")
    private final String insertTimeFields = "createTime,editTime";

    @Value("${auto-framework-config.auto-fill-field.update-time-fields}")
    private final String updateTimeFields = "editTime";

    /*intercept拦截：拦截目标对象的目标方法的执行*/
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = sdf.format(date);

        //添加时需要填充当前时间的字段名
//        String[] insertTimeFields = new String[]{"createTime", "editTime", "time", "updateTime"};
        String[] insertTimeFields1 = insertTimeFields.split(",");
        //更新时需要填充当前时间的字段名
//        String[] updateTimeFields = new String[]{"editTime", "updateTime"};
        String[] updateTimeFields1 = updateTimeFields.split(",");

        try {
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
            Object parameter = invocation.getArgs()[1];
            Object param1 = convertUtil.getRealParam(parameter);
            if (param1 != null) {
                List<Field> declaredFields = BeanUtil.getFieldsWithAnnotation(null, param1.getClass());
                if (sqlCommandType.name().equals("INSERT")) {
                    for (Field field : declaredFields) {
                        if (ArrayUtils.contains(insertTimeFields1, field.getName())) {
                            if (field.getType().equals(String.class))
                                BeanUtil.setFieldValue(param1, field.getName(), dateString);
                            else if (field.getType().equals(Date.class))
                                BeanUtil.setFieldValue(param1, field.getName(), date);
                        }
                    }
                } else if (sqlCommandType.name().equals("UPDATE")) {
                    for (Field field : declaredFields) {
                        if (ArrayUtils.contains(updateTimeFields1, field.getName())) {
                            if (field.getType().equals(String.class))
                                BeanUtil.setFieldValue(param1, field.getName(), dateString);
                            else if (field.getType().equals(Date.class))
                                BeanUtil.setFieldValue(param1, field.getName(), date);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new AutoException(ExceptionEnum.PLUGIN, "mybatis插件错误 caused by: " + e.getCause().getMessage());
        }
        return invocation.proceed();
    }

    /*plugin：包装目标对象（为目标对象创建一个代理对象）*/
    @Override
    public Object plugin(Object target) {
        Object wrap = Plugin.wrap(target, this);
        return wrap;
    }

    //将插件注册时的property属性设置进来
    @Override
    public void setProperties(Properties properties) {

    }

}
